//
//  ViewController.m
//  JSON的序列化
//
//  Created by 伍银荣 on 2021/9/4.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"
#import "SchoolManager.h"
#import "Student.h"
#import "Teacher.h"

#import "Video.h"

@interface ViewController ()


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //JSON的反序列化: 将JSON类型的字符串转换成OC对象
    //获取json文件
    NSString *path = [[NSBundle mainBundle]pathForResource:@"file.json" ofType:nil];
    NSData *data = [NSData dataWithContentsOfFile:path];
    //JSON的反序列化：奖JSON字符串转化成对象
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    //NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    NSLog(@"dict = %@",dict);
    //字典转模型
    SchoolManager *man = [SchoolManager schoolManagerWithDict:dict];
    NSLog(@"man = %@",man.student);
    
   
   
//    NSString *studentID = dict[@"studentID"];
//    NSLog(@"stuID = %@",studentID);
    
    
    
    
    
    //JSON的序列化: 将OC对象转成JSON类型的字符串,便于后台解析数据
    NSDictionary *dict2 = @{@"name":@"李四", @"age":@(17), @"gander": @"male"};
    NSData *data2 = [NSJSONSerialization dataWithJSONObject:dict2 options:0 error:NULL];
    NSString *str = [[NSString alloc]initWithData:data2 encoding:NSUTF8StringEncoding];
    NSLog(@"str = %@",str);
    
    
    NSArray *arr4 = @[
                      @{@"name":@"李四", @"age":@(17), @"gander": @"male"},
                      @{@"name":@"韩梅梅", @"age":@(24), @"gander": @"female"},
                      @{@"name":@"天真", @"age":@(54), @"gander": @"female"}
                      ];
    NSData *data3 = [NSJSONSerialization dataWithJSONObject:arr4 options:0 error:NULL];
    NSString *str2 = [[NSString alloc]initWithData:data3 encoding:NSUTF8StringEncoding];
    NSLog(@"str2 = %@",str2);
    
    //自定义对象进行JSON解析
    Video *video = [[Video alloc]init];
    video.videoName = @"ll-001.avi";
    video.size = 500;
    video.author = @"lilei";
    //使用kvc给对象内部的成员变量赋值
    [video setValue:@(YES) forKey:@"_isYellow"];
    
    NSLog(@"video = %@",video);
    //自定义对象不能进行JOSN序列化,必须先把自定义对象转化成数组或字典
    //将自定义对象转化成字典,需要通过kvc拿到对象的键可以获取对象的值
    NSDictionary *dict3 = [video dictionaryWithValuesForKeys:@[@"videoName", @"size", @"author", @"_isYellow"]];
    //判断该对象是否可以进行JSON序列化
    if (![NSJSONSerialization isValidJSONObject:dict3]) {
        //如果序列化无效
        NSLog(@"sorry,对象不能进行JSON序列化!!!");
        return;
    }
    
    NSData *data4 = [NSJSONSerialization dataWithJSONObject:dict3 options:0 error:NULL];
    //将data类型的二进制数据转化成NSString字符串类型
    NSString *str5 = [[NSString alloc]initWithData:data4 encoding:NSUTF8StringEncoding];
    NSLog(@"str5 = %@",str5);

    // xxxxxxxxxx
    
}


@end
